﻿using System;
using System.Windows.Forms;
using System.IO;

namespace VisualPureBasicIDE.CoreGUI.OptionPanels
{
    public partial class Compiler_GeneralPanel : OptionsPanel
    {
        public Compiler_GeneralPanel()
        {
            InitializeComponent();
        }

        private void ButtonBrowseClick(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
                textBoxCompiler.Text = openFileDialog.FileName;
        }

        private void ButtonAutomaticSearchClick(object sender, EventArgs e)
        {
            buttonAutomaticSearch.Enabled = false;

            // Show a nice action progress dialog
            var progressDialog = new ActionProgressDialog
                                   {
                                       Description = "Searching compiler executable..."
                                   };

            ActionProgressDialog.ShowMultithreaded(progressDialog);

            // Recursively search all drives for the executable
            foreach (var drive in DriveInfo.GetDrives())
            {
                var result = SearchCompilerExecutable(drive.RootDirectory.FullName);
                if (result.Length <= 0) continue;
                ActionProgressDialog.CloseMultithreaded(progressDialog);
                buttonAutomaticSearch.Enabled = true;

                if (MessageBox.Show("Compiler executable found: " + result + ". Use?", "Automatic search completed", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    textBoxCompiler.Text = result;

                return;
            }

            ActionProgressDialog.CloseMultithreaded(progressDialog);

            MessageBox.Show("The compiler executable could not be found", "Automatic search failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            buttonAutomaticSearch.Enabled = true;
        }

        private static string SearchCompilerExecutable(string startDirectory)
        {
            var directory = new DirectoryInfo(startDirectory);
            var files = new FileInfo[] { };
            try { files = directory.GetFiles(); }
            catch
            { }

            foreach (var file in files)
            {
                if (file.Name.Equals("PBCompiler.exe"))
                    return file.FullName;
            }

            var subDirectories = new DirectoryInfo[] { };
            try { subDirectories = directory.GetDirectories(); }
            catch
            {}

            foreach (var subDirectory in subDirectories)
            {
                var result = SearchCompilerExecutable(subDirectory.FullName);
                if (result.Length > 0)
                {
                    return result;
                }
            }

            return "";
        }
    }
}